import 'dart:async';

import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class WaveBubble extends StatefulWidget {
  final String path;

  const WaveBubble({
    super.key,
    required this.path,
  });

  @override
  State<WaveBubble> createState() => _WaveBubbleState();
}

class _WaveBubbleState extends State<WaveBubble> {
  late PlayerController controller;
  late StreamSubscription<PlayerState> playerStateSubscription;

  final playerWaveStyle = PlayerWaveStyle(
    fixedWaveColor: Colors.blue.withOpacity(0.3),
    liveWaveColor: Colors.blue,
    seekLineColor: Colors.red,
    seekLineThickness: 1,
    waveThickness: 2,
    scaleFactor: 300,
    spacing: 3,
  );

  @override
  void initState() {
    super.initState();
    controller = PlayerController();
    _preparePlayer();
    playerStateSubscription = controller.onPlayerStateChanged.listen((_) {
      controller.setRate(0.5);
      setState(() {});
    });
  }

  void _preparePlayer() async {
    // Prepare player with extracting waveform if index is even.
    controller.preparePlayer(
      path: widget.path,
      shouldExtractWaveform: true,
    );
  }

  @override
  void dispose() {
    playerStateSubscription.cancel();
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (!controller.playerState.isStopped)
            IconButton(
              onPressed: () async {
                controller.playerState.isPlaying
                    ? await controller.pausePlayer()
                    : await controller.startPlayer();
                controller.setFinishMode(finishMode: FinishMode.loop);
              },
              icon: Icon(
                controller.playerState.isPlaying
                    ? Icons.stop
                    : Icons.play_arrow,
              ),
              color: Colors.blue,
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
            ),
          AudioFileWaveforms(
            size: Size(MediaQuery.of(context).size.width, 112),
            playerController: controller,
            waveformType: WaveformType.long,
            playerWaveStyle: playerWaveStyle,
          ),
        ],
      ),
    );
  }
}
